package ctrl

import (
	"bytes"
	"errors"
	"io"
	"path/filepath"
	"strings"

	"gitee.com/extrame/tujiang/http/model"
	"gitee.com/extrame/tujiang/ocr"
	"github.com/extrame/goblet"
	"github.com/google/uuid"
)

type Ocr struct {
	System *ocr.OCRSystem
}

func (o *Ocr) Recognize(ctx *goblet.Context, args struct {
	Image *goblet.File `json:"image" form:"image" query:"image" goblet:"image"`
}) ([]ocr.OCRText, error) {

	bts, err := io.ReadAll(args.Image)

	if err != nil {
		return nil, err
	}

	var fileName = args.Image.Name
	var extention = fileName[strings.LastIndex(fileName, ".")+1:]

	if extention != "jpg" && extention != "jpeg" && extention != "png" {
		return nil, errors.New("only support image endswith jpg/jpeg/png")
	}

	var request model.Request

	//todo get app id
	//request.AppId =

	request.Path = uuid.New().String() + "." + extention

	// var newName = uuid.New().String() + "." + extention

	var buf bytes.Buffer

	_, err = buf.Write(bts)

	if err != nil {
		return nil, err
	}

	ctx.Server.SaveInPrivate(filepath.Join("request", request.Path), &buf)

	if err != nil {
		return nil, err
	}

	img, err := ocr.ReadBytes(bts)

	if err != nil {
		return nil, err
	}

	goblet.DB.Insert(&request)

	results := o.System.PredictOneImage(img)
	return results, nil
}
